<template>
  <div>
    <el-dialog
      :model-value="props.dialogVisible"
      :title="props.formStatus === 1 ? '编辑固件' : '新增固件'"
      width="500px"
      :close-on-click-modal="false"
      :before-close="handleClose">
      <el-form ref="firmwareFormRef" :model="firmwareForm" :rules="firmwareFormRules" label-width="120px" @submit.prevent>
        <el-form-item label="产品：" prop="productId">
          <el-select v-model="firmwareForm.productId" clearable placeholder="请选择产品" style="width: 100%;">
            <el-option
              v-for="item in productOptions"
              :key="item.productId"
              :label="item.name"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="固件版本名称：" prop="name">
          <el-input v-model="firmwareForm.name" clearable placeholder="请输入固件版本名称"></el-input>
        </el-form-item>
        <el-form-item label="固件安装包：" prop="data" v-if="props.formStatus !== 1">
          <el-upload
            ref="upload"
            class="upload-btn"
            accept=".zip"
            :show-file-list="true"
            :auto-upload="false"
            :on-change="changeFile">
            <el-button>上传文件</el-button>
          </el-upload>
          <span class="file-name">{{fileName}}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit(firmwareFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="FirmwareModifyForm">
import { ref, reactive, watch, ComponentInternalInstance, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { productList } from '@/api/product-manage'
import { firmwareInsert, firmwareUpdate } from '@/api/firmware-manage'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const emit = defineEmits(['submit', 'update:dialogVisible'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  formStatus: {
    type: Number,
    default: 0
  },
  formData: {
    type: Object,
    default: {}
  }
})

const productOptions = ref<any>([])
const firmwareForm = reactive({
  id: -1,
  productId: '',
  name: '',
  data: <any>null,
  size: ''
})
const firmwareFormRef = ref<FormInstance>()
const firmwareFormRules = reactive<FormRules>({
  productId: [
    { required: true, message: '请选择产品！' }
  ],
  name: [
    { required: true, message: '请输入固件版本名称！' }
  ],
  data: [
    { required: true, message: '请上传固件安装包！' }
  ]
})
const upload = ref<any>(null)
const fileName = ref('')

watch(() => props.dialogVisible, async (newVal) => {
  if (newVal) {
    getProductList()
    if (props.formStatus === 1) {
      firmwareForm.id = props.formData.id
      firmwareForm.name = props.formData.firmwareName
      firmwareForm.productId = props.formData.productId
    }
  }
})

// 上传改变事件
const changeFile = (file: any) => {
  if (file.raw.size / 1024 / 1024 > 16) {
    ElMessage.error('上传固件不能超过 16MB！')
    return false
  }
  let leng = file.name.length
  if (file.name.substring(leng - 4, leng) !== '.zip') {
    ElMessage.error('上传固件文件必须为 zip文件！')
    return false
  }
  firmwareForm.size = filterSize(file.size)
  fileName.value = file.name
  firmwareForm.data = file.raw
  firmwareFormRef.value?.validateField('data')
  // const reader = new FileReader()
  // // reader.readAsDataURL(file.raw)
  // // reader.readAsArrayBuffer(file.raw)
  // reader.onload = () => {
  //   // console.log(reader.result)
  //   firmwareForm.data = reader.result
  //   firmwareFormRef.value?.validateField('data')
  // }
}

// 处理文件大小
const filterSize = (size: number) => {
  let str = ''
  if (size / 1024 / 1024 > 1) {
    str = `${(size / 1024 / 1024).toFixed(2)} MB`
  } else {
    str = `${(size / 1024).toFixed(2)} KB`
  }
  return str
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  fileName.value = ''
  firmwareForm.size = ''
  resetForm(firmwareFormRef.value)
  proxy?.$emit('update:dialogVisible', false)
}

// 提交表单
const handleSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      if (props.formStatus === 0) {
        let { id, ...params } = firmwareForm
        await firmwareInsert(params).then((res: any) => {
          if (res.code === 0) {
            ElMessage.success(`新增成功！`)
            emit('submit')
            handleClose()
          } else {
            ElMessage.error(`${res.msg}`)
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        let { data, size, ...params } = firmwareForm
        // let params = Object.assign({}, firmwareForm)
        await firmwareUpdate(params).then((res: any) => {
          if (res.code === 0) {
            ElMessage.success(`编辑成功！`)
            emit('submit')
            handleClose()
          } else {
            ElMessage.error(`${res.msg}`)
          }
        }).catch(err => {
          console.log(err)
        })
      }
    }
  })
}

// 获取产品列表数据
const getProductList = async () => {
  await productList().then((res: any) => {
    if (res.code === 0) {
      productOptions.value = [...res.list]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}
</script>

<style lang="stylus" scoped>
.upload-btn
  display inline-flex
  align-items center
  line-height 1
  justify-content center
  vertical-align middle
  &:deep(.el-upload-list)
    display none
.file-name
  margin-left 10px
  color #409eff
</style>
